#include "stdafx.h"
#include "IExample.h"
#include "MyClassFactory.h"
#include "PortList.h"
#include "NetCardList.h"

HRESULT STDAPICALLTYPE DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
{
    if (!IsEqualCLSID(rclsid, CLSID_IExample))
    {
        *ppv = 0;
        return CLASS_E_CLASSNOTAVAILABLE;
    }
    return ClassFactory.QueryInterface(riid, ppv);
}

HRESULT STDAPICALLTYPE DllCanUnloadNow()
{
    return OutstandingObjects || LockCount ? S_FALSE : S_OK;
}

void Trace(LPCTSTR format, ...)
{
    va_list ap;
    va_start(ap, format);
    TCHAR sz[256];
    _vstprintf_s(sz, _countof(sz), format, ap);
    va_end(ap);
    OutputDebugString(sz);
}

BOOL WINAPI DllMain(HINSTANCE instance, DWORD fdwReason, LPVOID lpvReserved)
{
    switch (fdwReason)
    {
    case DLL_PROCESS_ATTACH:
        {
            // No TypeInfo yet loaded
            ExampleTypeInfo = NULL;
            CollectionTypeInfo = NULL;

            // Clear global counts
            OutstandingObjects = LockCount = 0;

            HRESULT hr = InitPortList();
            if (FAILED(hr))
            {
                Trace(_T("InitPortList failed with error code: %x\n"), hr);
                return FALSE;
            }

            hr = InitNetCardList();
            if (FAILED(hr))
            {
                Trace(_T("InitNetCardList failed with error code: %x\n"), hr);
                return FALSE;
            }

            // We don't need to do any thread initialization
            DisableThreadLibraryCalls(instance);
            break;
        }

    case DLL_PROCESS_DETACH:
        {
            // Release any TYPEINFO that my IDispatch functions got
            if (ExampleTypeInfo) ExampleTypeInfo->Release();
            if (CollectionTypeInfo) CollectionTypeInfo->Release();
        }
    }

    return TRUE;
}
